<template>
  <div class="app-container">
    <div class="card-wrap padding20 flex">

      <div v-for="(item, index) in tabs" :key="index" @click="tabClick(index)" :class="item.check?'tab-active':'tab-normal'">
        {{ item.name }}<span v-if="index>0">({{ item.count }})</span>
      </div>

    </div>

    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">

      <el-col :span="6">
        <el-form-item label="合同禀议编号:" prop="contractReportNumber">
          <el-input maxlength="30" v-model="queryParams.contractReportNumber" clearable placeholder="请输入合同禀议编号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车牌号/车架号:" prop="carNoVinNo">
          <el-input maxlength="30" v-model="queryParams.carNoVinNo" clearable placeholder="请输入车牌号/车架号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="品牌/车系/车型:" prop="modelId">
          <linkage-select placeholder="请选择品牌/车系/车型" v-model="linkageList" :check-strictly="false" style="width: 100%" @changeNode="linkageChange" />
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆产权:" prop="propertyRightName">

          <el-select placeholder="请选择车辆产权" filterable v-model="queryParams.propertyRightName" clearable style="width: 100%">
            <template v-for="(item, index) in companyOriginList">
              <el-option :label="item.deptName" :value="item.deptName" :key="index"></el-option>
            </template>
          </el-select>

        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆归属:" prop="ascriptionId">

          <el-select placeholder="请选择车辆归属" filterable @change="belongChange" v-model="queryParams.ascriptionId" clearable style="width: 100%">
            <template v-for="(item, index) in belongCompanyList">
              <el-option :label="item.deptName" :value="item.deptId" :key="index"></el-option>
            </template>
          </el-select>

        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆大区:" prop="cityId">

          <RegionCityLink v-model="queryParams.citydata" placeholder="请选择车辆大区" ref="citySelect" :showAllLevels="false" :defaultSelect="selIds" @change="citySelectionChange"></RegionCityLink>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆运营城市:" prop="operationsName">
          <el-input maxlength="30" v-model="queryParams.operationsName" clearable placeholder="请输入车辆运营城市"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="工单状态:" prop="workOrderStatus">
          <el-select placeholder="请选择工单状态" filterable v-model="queryParams.workOrderStatus" clearable>
            <template v-for="dict in dict.type.gps_workorder_status">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="采购禀议编号:" prop="procurementReportNumber">
          <el-input maxlength="30" v-model="queryParams.procurementReportNumber" clearable placeholder="请输入采购禀议编号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户名称:" prop="customerName">
          <el-input maxlength="30" v-model="queryParams.customerName" clearable placeholder="请输入客户名称"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="产品类型:" prop="contractType">
          <el-select filterable clearable v-model="queryParams.contractType" placeholder="请选择产品类型" style="width: 100%;">
            <el-option v-for="item in dict.type.quota_rent_type" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">

        <el-form-item label="车辆状态:" prop="carStatus">
          <el-select filterable clearable v-model="queryParams.carStatus" placeholder="请选择车辆状态">
<!--            <el-option v-for="item in businessTypeList" :key="item.value" :label="item.label" :value="item.value">-->
<!--            </el-option>-->
              <el-option v-for="item in dict.type.car_business_type" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>

      </el-col>

      <!--            <el-col :span="6">-->
      <!--                <el-form-item label="工单创建时间:">-->
      <!--                    <el-date-picker v-model="dateValue" type="daterange" range-separator="-"-->
      <!--                                    start-placeholder="开始日期" unlink-panels-->
      <!--                                    end-placeholder="结束日期" value-format='yyyy-MM-dd' clearable-->
      <!--                                    @change='changeDate'>-->
      <!--                    </el-date-picker>-->
      <!--                </el-form-item>-->
      <!--            </el-col>-->

      <el-col :span="6">
        <el-form-item label="工单类型:" prop="workOrderType">
          <el-select filterable clearable v-model="queryParams.workOrderType" placeholder="请选择工单类型" style="width: 100%;">
            <el-option v-for="item in dict.type.gps_workorder_type" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

        <el-col :span="6">
            <el-form-item label="批次号:" prop="flowBusinessId">
                <el-input maxlength="50" v-model="queryParams.flowBusinessId" clearable placeholder="请输入批次号"></el-input>
            </el-form-item>
        </el-col>
    </SearchContent>

    <div class="tablePage">
      <div class="card-wrap card-padding">
        <div class="table-title-wrap justify-end">
          <el-button type="primary" v-hasPermi="['GPSManage:GPSWorkOrder:add']" @click="handleWorkOrderAdd" size="mini">新增
          </el-button>
          <el-button v-hasPermi="['GPSManage:GPSWorkOrder:batchhandle']" type="success" @click="putin" size="mini">批量处理</el-button>

          <!--                    <el-button type="" icon="el-icon-upload2" size="mini"-->
          <!--                    >导出</el-button-->
          <!--                    >-->
        </div>
        <table-page ref="el-table" rowKey="id" v-loading="loading" :dataList="datalist" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :border="true" :isSelect="false" @setSizeCurrent="getList" @selectionChange="selectionChange" @selection-change="selectionChange">

          <!-- 操作插槽 -->
          <template slot="tableColAc">
            <!-- 是否多选 :selectable="row=>row.workOrderType==12 && (row.workOrderStatus==1 || '退回到发起人' == row.auditStatus)"-->
            <el-table-column type="selection" :reserve-selection="true" width="55" align="center" :selectable="row=>row.workOrderType==12 && (row.workOrderStatus==1 || '退回到发起人' == row.auditStatus)" />
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <div>
<!--                    工单状态(1.未处理 2.处理中 3.已完成)-->
<!--                    退回到发起人-->
                  <el-button v-hasPermi="['GPSManage:GPSWorkOrder:handle']" type="text" v-if="scope.row.workOrderStatus == 1 || '退回到发起人' == scope.row.auditStatus" @click="goHandle(scope.row)">处理
                  </el-button>
                  <el-button v-hasPermi="['GPSManage:GPSWorkOrder:view']" type="text" v-if="scope.row.workOrderStatus == 2 || scope.row.workOrderStatus == 3" @click="goDetail(scope.row)">查看
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-for="item in tableItem" :label="item.label" align="center" :min-width="item.minWidth" show-overflow-tooltip>
              <template slot-scope="scope">
                <template v-if="!item.filterable">
                  {{ scope.row[item.prop]|filterNull }}
                </template>
                <template v-else>{{
                                        item.filter(scope.row)
                                    }}
                </template>
              </template>
            </el-table-column>
          </template>
        </table-page>
      </div>
    </div>

    <!-- 新增账号 -->
    <AddWorkOrder ref="addWorkOrder" @success="handleAccountQuery"></AddWorkOrder>
  </div>
</template>
<script>
import Cookies from "js-cookie";
import ShortcutDate from "@/views/components/ShortcutDate/index.vue";
import RegionCityLink from "@/views/components/provinceCity/regionCityLink.vue";
import SearchContent from "@/components/SearchContent/index.vue";
import LinkageSelect from "@/views/components/linkageSelect.vue";
import { listDept } from "@/api/system/dept";
import AddWorkOrder from "@/views/GPSManage/GPSWorkOrder/addWorkOrder.vue";
import { gpsInstallCount, gpslist } from "@/api/gps/gpsList.js";

export default {
  name: "GPSWorkOrderList",
  components: { AddWorkOrder, LinkageSelect, SearchContent, RegionCityLink, ShortcutDate },
  dicts: ["gps_workorder_status", 'quota_rent_type', 'gps_workorder_type', 'car_business_type'],
  mixins: [],
  props: {},
  data() {
    return {
      loading: false,
      tableItem: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractReportNumber: null,
        carNoVinNo: null,
        ascriptionId: null,
        propertyRightName: null,
        operationsName: null,
        workOrderStatus: null,
        procurementReportNumber: null,
        customerName: null,
        contractType: null,
        carStatus: null,
        workOrderType: null,
          flowBusinessId: null,
        citydata: [],
      },
      datalist: [],
      total: 0,
      dicts: {},
      selected: [],
      citySelection: [],
      linkageList: [],
      belongCompanyList: [],
      companyOriginList: [],
      timeRange: [],
      selIds: [],
      dateValue: [],
      tabs: [{
        name: '全部',
        count: 0,
        check: true
      }, {
        name: 'GPS安装工单',
        count: 0,
        check: false
      }],
    };
  },
  computed: {
    userId() {
      return Cookies.get("userId");
    },
  },
  watch: {},
  mounted() {
    this.init();
  },
  activated() {
    this.getList()
  },
  methods: {
    goHandle(row) {
      console.log('row', row)

      if (row.workOrderType == 12) {
        // this.$router.push({
        this._toPage({
          name: 'GPSInstall',
          query: {
            // data:[row],
            carIds: row.carId,
            workOrderType: row.workOrderType,
            // ids: row.workOrderCode,
            type: 'write',
            pageType: 'GPS安装工单申请'
          },
        })
      } else if (row.workOrderType == 13) {
        // this.$router.push({
        this._toPage({
          name: 'GPSRenewal',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'write',
            pageType: 'GPS续费工单申请'
          },
        })
      } else if (row.workOrderType == 14) {
        // this.$router.push({
        this._toPage({
          name: 'GPSFix',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'write',
            pageType: 'GPS维修工单申请'
          },
        })
      } else if (row.workOrderType == 15) {
        // this.$router.push({
        this._toPage({
          name: 'GPSRemove',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'write',
            pageType: 'GPS拆除工单申请'
          },
        })
      } else if (row.workOrderType == 17) {
        // this.$router.push({
        this._toPage({
          name: 'GPSCheck',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'write',
            pageType: 'GPS排查工单申请'
          },
        })
      }

    },
    goDetail(row) {
      if (row.workOrderType == 12) {
        // this.$router.push({
        this._toPage({
          name: 'GPSInstall',
          query: {
            // data: [row],
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'disabled',
            pageType: 'GPS安装工单详情'
          },
        })
      } else if (row.workOrderType == 13) {
        // this.$router.push({
        this._toPage({
          name: 'GPSRenewal',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'disabled',
            pageType: 'GPS续费工单详情'
          },
        })
      } else if (row.workOrderType == 14) {
        // this.$router.push({
        this._toPage({
          name: 'GPSFix',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'disabled',
            pageType: 'GPS维修工单详情'
          },
        })
      } else if (row.workOrderType == 15) {
        // this.$router.push({
        this._toPage({
          name: 'GPSRemove',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'disabled',
            pageType: 'GPS拆除工单详情'
          },
        })
      } else if (row.workOrderType == 17) {
        // this.$router.push({
        this._toPage({
          name: 'GPSCheck',
          query: {
            // data: row,
            carIds: row.carId,
            workOrderType: row.workOrderType,
            type: 'disabled',
            pageType: 'GPS排查工单详情'
          },
        })
      }
    },
    handleAccountQuery() {
      this.handleQuery();
    },
    handleWorkOrderAdd() {
      this.$refs.addWorkOrder.show(0);
    },
    putin() {
      if (this.selected?.length == 0) {
        this.$message({
          message: "请先选择列表",
          type: "warning",
        });
        return;
      }

      console.log('putin', this.selected)

      const unSel = this.selected.find(item => {
        return item.workOrderType != 12 || (item.workOrderStatus != 1 && '退回到发起人' != item.auditStatus)
        // return item.workOrderType != 12 || item.workOrderStatus != 1
      })

      if (unSel) {
        this.$message({
          message: "仅未处理的安装工单可以批量处理",
          type: "warning",
        });
        return;
      }

      const dum = this.selected.find(item=>{
          return item.contractReportNumber !== this.selected[0].contractReportNumber || item.customerName !== this.selected[0].customerName
      })

        if(dum){
            this.$message({
                message: "同一订单号且同一客户才能批量处理",
                type: "warning",
            });
            return;
        }


      // if (this.selected[0]?.flowId) {
      //     this.$message({
      //         message: "此项已经提报",
      //         type: "error",
      //     });
      //     return;
      // }
      // console.log(this.selected);

      // this.$router.push({
      this._toPage({
        name: 'GPSInstall',
        query: {
          // data:this.selected,
          carIds: this.selected.map(item => item.carId).join(","),
          workOrderType: this.selected[0].workOrderType,
          // ids: ids,
          type: 'write',
          pageType: 'GPS安装工单申请'
        }
      })

    },
    selectionChange(val) {
      console.log(val, 'val');
      this.selected = val;
    },
    init() {
      this.initTable();
      this.getList();
      this.getCompanyOrigin();
    },
    initTable() {
      this.tableItem = [
        {
          label: "批次号",
          prop: "flowBusinessId",
          type: "text",
          minWidth: "210px",
        },
        {
          label: "GPS工单编号",
          prop: "workOrderCode",
          type: "text",
          minWidth: "210px",
        },
        {
          label: "车辆产权",
          prop: "propertyRightName",
          type: "text",
          minWidth: "210px",
        },
        {
          label: "车辆归属",
          prop: "ascription",
          type: "text",
          minWidth: "210px",
        },
        {
          label: "车辆大区",
          prop: "region",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "车辆运营城市",
          prop: "operationsName",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "车架号",
          prop: "vinNo",
          minWidth: '190',
          type: "text",
        },
        {
          label: "品牌/车型",
          prop: "brandName",
          type: "text",
          minWidth: '310',
          filterable: true,
          filter: val => {
            return (val.brandName ? val.brandName : '--') + '/' + (val.seriesName ? val.seriesName : '--') + '/' + (val.modelName ? val.modelName : '--')
          }
        },
        {
          label: "车辆状态",
          prop: "businessType",
          type: "text",
            minWidth: '90',
          filterable: true,
          filter: (val) => {
            let result = [];
              this.dict.type.car_business_type?.map((item) => {
                  if ((item.value * 1) == val.businessType) {
                      result.push(item.label);
                  }
              });
              return result && result?.join("/");
            // this.businessTypeList?.map((item) => {
            //   if ((item.value * 1) == val.businessType) {
            //     result.push(item.label);
            //   }
            // });
            // return (result && result?.join("/")) || '--';
          },
        },
          {
              label: "审批状态",
              prop: "auditStatus",
              minWidth: '190',
              type: "text",
          },
        {
          label: "工单类型",
          prop: "workOrderStatus",
          type: "text",
          minWidth: '170',
          filterable: true,
          filter: (val) => {
            let result = [];
            this.dict.type.gps_workorder_type?.map((item) => {
              if ((item.value * 1) == val.workOrderType) {
                result.push(item.label);
              }
            });
            return (result && result?.join("/")) || '--';
          },
        },
        {
          label: "客户名称",
          prop: "customerName",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "产品类型",
          prop: "contractType",
          type: "text",
          minWidth: "150px",
          filterable: true,
          filter: (val) => {
            let result = [];
            this.dict.type.quota_rent_type?.map((item) => {
              if ((item.value * 1) == val.contractType) {
                result.push(item.label);
              }
            });
            return (result && result?.join("/")) || '--';
          },
        },
        {
          label: "合同开始日期",
          prop: "contractStartTime",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "合同结束日期",
          prop: "contractEndTime",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "合同禀议编号",
          prop: "contractReportNumber",
          type: "text",
          minWidth: "190px",
        },
        {
          label: "工单状态",
          prop: "workOrderStatus",
          type: "text",
          filterable: true,
          minWidth: "130px",
          filter: (val) => {
            let result = [];
            this.dict.type.gps_workorder_status?.map((item) => {
              if ((item.value * 1) == val.workOrderStatus) {
                result.push(item.label);
              }
            });
            return (result && result?.join("/")) || '--';
          },
        },
        {
          label: "采购禀议编号",
          prop: "procurementReportNumber",
          type: "text",
          minWidth: "220px",
        },
        {
          label: "处理人",
          prop: "processedByName",
          type: "text",
          minWidth: "100px",
        },
        {
          label: "处理时间",
          prop: "processedByTime",
          type: "text",
          minWidth: "150px",
        },
        {
          label: "工单创建时间",
          prop: "createTime",
          type: "text",
          minWidth: "150px",
        },

        // {
        //     label: "报销类型",
        //     prop: "businessTypes",
        //     type: "text",
        //     filterable: true,
        //     minWidth: "150px",
        //     filter: (val) => {
        //         let result = [];
        //         this.dict.type.expense_business_type?.map((item) => {
        //             if (val.businessTypes?.includes(item.value * 1)) {
        //                 result.push(item.label);
        //             }
        //         });
        //         return (result && result?.join("/")) || '--';
        //     },
        // },

        // {
        //     label: "产品类型",
        //     prop: "contractType",
        //     type: "text",
        //     filterable: true,
        //     filter: (val) => {
        //         let val_raw = val.contractType?.split(",");
        //
        //         let result = [],
        //             word = "";
        //         let el = this.dicts.contractType.map((item) => {
        //             if (val_raw.includes(item.value)) {
        //                 result.push(item.label);
        //             }
        //         });
        //         word = result?.join("/") ?? "-";
        //         return word;
        //     },
        // },
      ];
    },
    getList() {
      this.loading = true;
      let params = this._.cloneDeep(this.queryParams);
      // params.businessType= params.businessType?.join(",");
      // params.contractType = params.contractType?.join("|");
      gpslist(params)
        .then((res) => {
          if (res.code == 200) {
            this.datalist = res.rows ?? [];
            this.total = res.total ?? 0;
          }
        })
        .finally(() => {
          this.loading = false;
        });
      gpsInstallCount(params).then(res => {
        this.tabs[1].count = res.data
      })
    },

    changeDate(val) {
      if (val) {
        this.queryParams.createStartTime = val[0]
        this.queryParams.createEndTime = val[1]
      } else {
        this.queryParams.createStartTime = ""
        this.queryParams.createEndTime = ""
      }
    },

    getCompanyOrigin() {
      listDept(
        {
          deptType: '2',//组织类型（1部门 2公司）
          regionId: null,//所在城市（省市区id）
        }).then(res => {
          this.companyOriginList = res.data
          this.belongCompanyList = res.data
        })
    },

    getBelongCompany() {
      listDept(
        {
          deptType: '2',//组织类型（1部门 2公司）
          regionId: this.queryParams.cityId,//所在城市（省市区id）
        }).then(res => {
          this.belongCompanyList = res.data
        })
    },

    citySelectionChange(val) {
      if (val.length > 0) {
        this.queryParams.region = val[0].pathNodes[0]?.label
        this.queryParams.regionId = val[0].pathNodes[0]?.value
        this.queryParams.provinceName = val[0].pathNodes[1]?.label
        this.queryParams.provinceId = val[0].pathNodes[1]?.value
        this.queryParams.cityName = val[0].pathNodes[2]?.label
        this.queryParams.cityId = val[0].pathNodes[2]?.value
      } else {
        this.queryParams.regionId = null
        this.queryParams.region = null
        this.queryParams.provinceName = null
        this.queryParams.provinceId = null
        this.queryParams.cityId = null
        this.queryParams.cityName = null
      }

      let find = this.belongCompanyList.find(item => this.queryParams.ascriptionId == item.deptId);

      if (this.queryParams.cityId && find && this.queryParams.cityId != find.regionId.split("/")[1]) {
        this.queryParams.belongCityName = null;
        this.queryParams.ascriptionId = null;
      }


      this.belongCompanyList = []
      this.getBelongCompany();
    },

    //归属
    belongChange(val) {
      let find = this.belongCompanyList.find(item => val == item.deptId);
      if (find) {
        this.queryParams.belongCityName = find.deptName ?? null
        console.log('belongChange', find)

        this.selIds = [find.areaId,
        find.regionId && find.regionId.split("/")[0],
        find.regionId && find.regionId.split("/")[1]
        ];
      } else {
        this.selIds = []
      }


    },
    async linkageChange(val) {
      this.linkageList = val
      if (val) {
        this.queryParams.brandId = val[0] ? val[0].id : ''
        this.queryParams.seriesId = val[1] ? val[1].id : ''
        this.queryParams.modelId = val[2] ? val[2].id : ''
        this.queryParams.brandName = val[0] ? val[0].name : ''
        this.queryParams.seriesName = val[1] ? val[1].name : ''
        this.queryParams.modelName = val[2] ? val[2].name : ''
      } else {
        this.queryParams.brandId = null
        this.queryParams.seriesId = null
        this.queryParams.modelId = null
        this.queryParams.brandName = null
        this.queryParams.seriesName = null
        this.queryParams.modelName = null
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.timeRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        contractReportNumber: null,
        carNoVinNo: null,
        ascriptionId: null,
        propertyRightName: null,
        operationsName: null,
        workOrderStatus: null,
        procurementReportNumber: null,
        customerName: null,
        contractType: null,
        carStatus: null,
        workOrderType: null,
          flowBusinessId: null,
        citydata: [],
      },
        this.checked = -1;
      this.selIds = []
      this.$refs['el-table'].table_clearSelection()
      this.citySelection = []
      this.dateValue = []
      this.linkageList = []
      this.selected = []
      this.tabClick(0)
      this.citySelectionChange([])
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    tabClick(index) {
      this.tabs.forEach((item, i) => {
        item.check = index == i;
      })

      this.queryParams.workOrderType = index == 1 ? '12' : null

      this.handleQuery()
    },
  },
};
</script>
<style lang="scss" scoped></style>
